﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using Bookvar.ApplicationModel;
using Bookvar.Common;
using Bookvar.ObjectModel;
using Bookvar.ServiceModel;
using BookvarWpf.Properties;
using BookvarWpf.Windows;
using Application=System.Windows.Application;
using LocalizationResources = Bookvar.UI.Localization.Resources;


namespace BookvarWpf
{
    public partial class BookvarNavigation
    {
        public BookvarNavigation()
        {
            InitializeComponent();

            Loaded += OnLoadCompleted;
        }

        private static FileSystemPersistenceService PersistenceService
        {
            get
            {
                return
                    BookvarApplication.Current.ServiceLayer.GetService<IPersistenceService>() as
                    FileSystemPersistenceService;
            }
        }

        private static IAutoSaveRecoveryService AutoSaveRecoveryService
        {
            get
            {
                return
                    BookvarApplication.Current.ServiceLayer.GetService<IAutoSaveRecoveryService>();
            }
        }

        private void OnLoadCompleted( object sender, RoutedEventArgs e )
        {
            Application.Current.MainWindow.WindowState = WindowState.Maximized;
            Application.Current.MainWindow.Title = LocalizationResources.BookvarTitleDefault;
            BookvarApplication.Current.ServiceLayer.AddService<IPersistenceService>( new FileSystemPersistenceService() );
            BookvarApplication.Current.ServiceLayer.AddService<IAutoSaveRecoveryService>(
                new FileSystemAutoSaveRecoveryService( Settings.Default.AutoRecoveryInterval ) );

            string[] args = Environment.GetCommandLineArgs();
            if ( args.Length > 1 )
            {
                if ( args.Length == 2 )
                {
                    if ( NavigationService != null )
                    {
                        NavigationService.Navigate( new MainPage( new List<string> { args[ 1 ] } ) );
                    }
                }

                // Old code for opening mind map from SharePoint and within a gadget
//                else if (args[1] == "-s")
//                {                    
//                    string fileName = String.Empty;
//					SaveFileDialog fileDialog = new SaveFileDialog();
//					fileDialog.Filter = "Bookvar MindMap (*.bmm)|*.bmm";
//					if (fileDialog.ShowDialog() == DialogResult.OK)
//					{
//						fileName = fileDialog.FileName;  
//                        WebClient webClient = new WebClient();
//                        webClient.Credentials =
//                            new NetworkCredential(Settings.Default.Username,
//                                                  Settings.Default.Password,
//                                                  Settings.Default.Password);
//                        webClient.DownloadFile(args[2], fileName);
//					    if ( NavigationService != null )
//					    {
//					        NavigationService.Navigate(new MainPage(fileName));
//					    }
//					}
//                }
            }

            foreach ( string recentFile in RecentFiles.All )
            {
                if ( File.Exists( recentFile ) )
                {
                    var newMap = new MindMap();
                    PersistenceService.RegisterMindmapForPersistence( newMap, recentFile );
                    Uri mapThumbnail = PersistenceService.LoadThumbnailFromPersistence( newMap.Key );
                    if ( mapThumbnail != null )
                    {
                        var info =
                            new ImageInfo( mapThumbnail, mapThumbnail, Path.GetFileName( recentFile ), recentFile );
                        imagesItemsControl.Items.Add( info );
                    }
                }
            }

            if ( AutoSaveRecoveryService.GetAutoSavedMaps().Count > 0 )
            {
                var recoveredMaps = new RecoveredMaps();
                if ( recoveredMaps.ShowDialog() == true )
                {
                    int recoveredMapIndex = 1;
                    var fileNames = new List<string>();
                    foreach ( RecoveredMapInfo mapInfo in recoveredMaps.SelectedRecoveredMaps )
                    {
                        string fileName;
                        if ( mapInfo.HasFileName )
                        {
                            fileName = Path.Combine(
                                Path.GetDirectoryName( mapInfo.FileName ),
                                string.Format( CultureInfo.CurrentCulture, "[{0}] {1}.bmm",
                                               LocalizationResources.RecoveredMapsRecoveredMap,
                                               Path.GetFileNameWithoutExtension( mapInfo.FileName ) ) );
                        }
                        else
                        {
                            fileName = Path.Combine(
                                Path.GetTempPath(),
                                string.Format( CultureInfo.CurrentCulture, "{0} {1}.bmm",
                                               LocalizationResources.RecoveredMapsRecoveredMap,
                                               recoveredMapIndex ) );
                            recoveredMapIndex++;
                        }

                        fileNames.Add( fileName );

                        AutoSaveRecoveryService.RecoverMapTo( mapInfo.Key, fileName );
                    }

                    if ( NavigationService != null )
                    {
                        NavigationService.Navigate( new MainPage( fileNames ) );
                    }
                }
            }
        }

        private void StartNewMindMap( object sender, MouseButtonEventArgs e )
        {
            if ( NavigationService != null )
            {
                NavigationService.Navigate( new MainPage() );
            }
        }

        private void OpenMindMap( object sender, MouseButtonEventArgs e )
        {
            var fileDialog = new OpenFileDialog();
            fileDialog.Filter = "Bookvar MindMap (*.bmm)|*.bmm";

            if ( fileDialog.ShowDialog() == DialogResult.OK )
            {
                string fileName = fileDialog.FileName;
                if ( NavigationService != null )
                {
                    NavigationService.Navigate( new MainPage( new List<string> { fileName } ) );
                }
            }
        }

        private void OpenRecentMindMap( object sender, MouseButtonEventArgs e )
        {
            var image = sender as Image;
            if ( image != null )
            {
                string mapPath = image.Tag.ToString();
                if ( NavigationService != null )
                {
                    NavigationService.Navigate( new MainPage( new List<string> { mapPath } ) );
                }
            }
        }
    }
}